using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;

namespace ValidacionForms
{
    [ProvideProperty("HandleError", typeof(Control))]
    class CustomErrorProvider : ErrorProvider     /*, IExtenderProvider*/, ISupportInitialize //, IBindingList
    {                                     // \> Component, IExtenderProvider, ISupportInitialize
        List<Control> HandleList = new List<Control>();
        public bool GetHandleError(Control control)
        {
            if (!_initialized) return true;
            return HandleList.Contains(control);
        }
        private void Remove(Control control)
        {
            if (HandleList.Contains(control))
            {
                HandleList.Remove(control);
                (control as INotifyValidationError).ValidationError -= new ValidationErrorDelegate(CustomErrorProvider_ValidationError);
                (control as INotifyValidationError).ValidationOk -= new ValidationOkDelegate(CustomErrorProvider_ValidationSuccess);
            }
        }
        public void SetHandleError(Control control, bool flag)
        {
            if (flag == false)
            {
                Remove(control);
            }
            else
            {
                if (!(control is INotifyValidationError))
                {
                    if (_initialized)
                        MessageBox.Show("Invalid value, " + control.Name + " must implement INotifiesValidationError");
                    if (HandleList.Contains(control))
                        Remove(control);
                }
                else
                {
                    HandleList.Add(control);
                    (control as INotifyValidationError).ValidationError -= new ValidationErrorDelegate(CustomErrorProvider_ValidationError);
                    (control as INotifyValidationError).ValidationError += new ValidationErrorDelegate(CustomErrorProvider_ValidationError);
                    (control as INotifyValidationError).ValidationOk -= new ValidationOkDelegate(CustomErrorProvider_ValidationSuccess);
                    (control as INotifyValidationError).ValidationOk += new ValidationOkDelegate(CustomErrorProvider_ValidationSuccess);
                }
            }
        }
        void CustomErrorProvider_ValidationSuccess(object sender)
        {
            this.SetError(sender as Control, "");
        }
        void CustomErrorProvider_ValidationError(object sender, object Error)
        {
            this.SetError(sender as Control, Error.ToString());
        }
        #region ISupportInitialize Members

        bool _initialized = false;
        void ISupportInitialize.BeginInit()
        {
            _initialized = false;
        }

        void ISupportInitialize.EndInit()
        {
            _initialized = true;
        }

        #endregion
    }

}
